package com.ddwanglife.juc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class AirCondition{
    private int number = 0;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();
    public void increment()throws Exception{
        lock.lock();
        try{
            //1 判断
            while(number != 0){
                condition.await();
            }
            //2 干活
            number++;
            System.out.println(Thread.currentThread().getName()+"\t"+number);
            //3 通知
            condition.signalAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally{
            lock.unlock();
        }
    }
    public void decrement()throws Exception{
       lock.lock();
       try{
           //1 判断
           while(number == 0){
               condition.await();
           }
           //2 干活
           number--;
           System.out.println(Thread.currentThread().getName()+"\t"+number);
           //3 通知
           condition.signalAll();
       }catch (Exception e){
           e.printStackTrace();
       }finally {
           lock.unlock();
       }

    }
}
/**
 * 两个线程，可以操作初始值为0的一个变量，实现一个线程
 * 对该变量加1，一个线程对该变量减1，实现交替，来10轮，变量初始值为0
 */
public class ProdConsumerDemo {
    public static void main(String[] args) {
        AirCondition airCondition = new AirCondition();
        new Thread(()->{
            for(int i = 1;i<=10;i++) {
                try {
                    airCondition.increment();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"A").start();
        new Thread(()->{
            for(int i = 1;i<=10;i++) {
                try {
                    airCondition.decrement();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"B").start();
    }
}
